<?php

/*
 * Controller/EmployeController.php
 */

namespace RHX\Controller;

use RHX\Helper\Number;
use Zend\View\Model\JsonModel;
use RHX\Helper\RHDateTime;
use RHX\Model\Object\XRules;
use Zend\Debug\Debug;
use RHX\Helper\Uploader;
use RHX\Model\Manager\FileManager;

class EmployeController extends RHXController {

    public function indexAction() {
        // Paramètres
        $siteId = $this->params()
                ->fromRoute('id', -1); 
        $refresh = $this->params()
                ->fromRoute('other1', 0);
        $page = $this->params()
                ->fromRoute('other2', 1);
        $perPage = $this->params()
                ->fromRoute('other3', 100);
        if ($perPage <= 0)
            $perPage = 100;

        // Tables
        $siteTable = $this->getService('Table\SiteTable');

        // Test
        $site = null;
        if ($siteId < 0) {
            // Site en Session
            $site = $this->navigation->offsetGet('site');
            
            $refresh = 1;
        } else {
            $site = $siteTable->get($siteId);
            // Changement de site
            $this->changeSite($siteId);
        }

        // SiteList
        $siteList = $siteTable->getAll();

        return array(
            'site' => $site,
            'refresh' => ($refresh == 0) ? false : true,
            'siteList' => $siteList,
            'page' => $page,
            'perPage' => $perPage,
        );
    }

    public function loadIndexAction() {
        // Changement de Layout
        $this->layout('layout/ajax');

        // Paramètres
        $siteId = $this->params()
                ->fromRoute('id', 1);
        // Changement de site
        $this->changeSite($siteId);
        $refresh = $this->params()
                ->fromRoute('other1', 1);
        $page = $this->params()
                ->fromRoute('other2', 1);
        $perPage = $this->params()
                ->fromRoute('other3', 100);
        if ($perPage <= 0)
            $perPage = 100;

        // Tables
        $employeTable = $this->getService('Table\EmployeTable');
        $siteTable = $this->getService('Table\SiteTable');

        // Liste des employés du Site
        $employeList =    $employeTable->getEmployesBySiteEx2($siteId, 'poste_rang asc, nom1 asc'/*, $page, $perPage*/);
        // Site
        $site = $siteTable->get($siteId);

        // Nombre de page
        $nbPage = $employeTable->getPageCount($siteId, $perPage);

        /*var_dump(count($employeList));*/
        
        return array(
            'employeList' => $employeList,
            'site' => $site,
            'nbPage' => $nbPage,
            'page' => $page,
            'refresh' => $refresh,
            
        );
    }

    public function jsonSiteListAction() {
        // Table
        $siteTable = $this->getService('Table\SiteTable');

        // Liste des sites
        $siteList = $siteTable->select(function(\Zend\Db\Sql\Select $select) {
            $select->order('id DESC');
        });
        $sites = array();
        foreach ($siteList as $site) {
            $sites[$site->id] = $site->libelle;
        }

        // JSON VIEW
        $jsonView = new \Zend\View\Model\JsonModel($sites);

        return $jsonView;
    }

    public function addAction() {
        // manager 
        $siteManager = new \RHX\Model\Manager\SiteManager($this->getAdapter());         
        $fileManager = new \RHX\Model\Manager\FileManager($this->getAdapter()) ;
        
        // tables
        $siteTable = $this->getService('Table\SiteTable');
        $siteHoraireTbl = $this->getService('Table\SiteHoraireTable');

        // Sites
        $siteId = $this->params()
                ->fromRoute('id', 1);

        // Site
        $site = $siteTable->get($siteId); 
        $siteHoraire = $siteHoraireTbl->getBySite($site->id);
        
        if(! $siteHoraire ){ // if has hot yet horraire then create one
            $siteHoraire = $siteManager->createSiteHoraire($site->id);       
        }

        // table collège
        $tableCollege = new \RHX\Model\Table\CollegeTable($this->getAdapter());
        $collegeDefault = $tableCollege->getAll()
                ->current();

        // table Contrat Type
        $tableContratType = new \RHX\Model\Table\ContratTypeTable($this->getAdapter());
        $contratTypeList = $tableContratType->getAll();
        $contratTypes = array();
        foreach ($contratTypeList as $type) {
            $contratTypes[(int) $type->id] = $type->libelle . ' (' . $type->abrev . ')';
        }

        return array(
            'site' => $site,
            'site_horaire' => $siteHoraire,
            'collegeDefault' => $collegeDefault,
            'contratTypes' => $contratTypes,
            'fileManager' => $fileManager
        );
    }

    /**
     * Edition d'un employé
     * 
     * @return array
     */
    public function editAction() {
        //config
        $config     = $this->getServiceLocator()->get('config');        
        $repUpl   = $config['upload_directory']['employe'];
        
        // Variables
        $matricule = (int) $this->params()
                        ->fromRoute('id', 0);

        // Tables
        $employeTable = $this->getService('Table\EmployeTable');
        
        // Manager
        $fileManager = new \RHX\Model\Manager\FileManager($this->getAdapter()) ;
        

        // Employe
        $employe = $employeTable->get($matricule);
        $copieEmploye = $employe;
        $oldVersion = array();
        $old = null;
        do {
            $old = $copieEmploye->getOld();
            if (!is_null($old)) {
                $oldVersion[] = $old;
                $copieEmploye = $old;
            }
        } while (!is_null($old));

        // liste des colleges
        $tableCollege = new \RHX\Model\Table\CollegeTable($this->getAdapter());
        $collegeList = $tableCollege->getAll();
        $colleges = array();
        foreach ($collegeList as $col) {
            $colleges[(int) $col->id] = $col->libelle;
        }
        
        /* heures modulées */
        
        $isLabo = $employe->site_id == 2; // site labo
        $hrModulee['is_labo'] = $isLabo; 
        if($isLabo){
            $hrModulee['value'] = $this->getHeuresModulee($matricule, date('y-m-d' ));
        }
       
        return array(
            'employe' => $employe,
            'employeHistory' => $oldVersion,
            'colleges' => $colleges,
            'repUpl' => $repUpl,
            'hrModulee' => $hrModulee,
            'fileManager' => $fileManager
        );
    }
    
    /* recupérer heures modulée d'un employé avant une date donnée
     * $matricule int id se l'employé
     * $day date
     */
    private function getHeuresModulee($matricule , $day){
        
        //tbl
        $planningSemTbl	 = $this->getService('Table\PlanningSemaineTable');
        $empTbl	 = $this->getService('Table\EmployeTable');
        
        $e = $empTbl->get($matricule);
        
        $calculator		 = new \RHX\Model\Object\XCalculator($e->getAdapter());
        
        $tot = 0.0;
        
        $now = date('y-m-d'); 
        
        //var_dump($now );
        $plans = $planningSemTbl->getByEmployeBeforeDay($matricule, $now);
        //var_dump('count > ' . count($plans));
        
        foreach ($plans as $p):                  
            $lundi = $p->lundi;
        
            $modulee = RHDateTime::toFloat( $calculator->getHeuresModulees($p)->totalHours() );            
            $heureDebdo = $e->getHoraireHebdo(true, $lundi);
            
            $diff = $modulee - $heureDebdo;
            //print($modulee.' - ' . $heureDebdo .  ' = ' . $diff . '<br>');            
            $tot += $diff;
        endforeach; 
        //print('total = '. $tot . '<br>');
        
        //var_dump($tot);
        return  \RHX\Helper\Number::frenchFormat($tot);

    }

    public function fireAction() {
        // Changement de layout
        $this->layout('layout/ajax');

        // Données en Post
        $post = $this->getRequest()->getPost();

        // Table
        $employeTable = $this->getService('Table\EmployeTable');

        // Employé
        $employe = $employeTable->get($post->get('matricule'));

        return array(
            'employe' => $employe,
        );
    }

    /**
     * Renvoyer un employé
     * 
     * @return array
     */
    public function fireEmployeAction() {
        // Changement de layout
        $this->layout('layout/ajax');

        // Table
        $employeTable = $this->getService('Table\EmployeTable');
        $planningSemaineTable = $this->getService('Table\PlanningSemaineTable');

        // Paramètres
        $matricule = $this->params()
                ->fromRoute('id', 0);
        $date = new RHDateTime();
        // $date->modify('next day');
        $this->fire($matricule, $date->date());

        // Employe
        /* $employe = $employeTable->get($matricule);

          $employe->actif = 0;
          $employeTable->save($employe);

          // Mise à jour des plannings Semaine de la semaine en cours
          // Effacement de l'employé des semaines avenir
          $result = $planningSemaineTable->fire($employe->matricule); */

        return array(
            'employe' => $employe,
            'result' => $result,
        );
    }

    public function jsonetatcivillistAction() {
        // Etat Civil
        $etatCivil = array(
            '1' => 'Monsieur',
            '2' => 'Madame',
            '3' => 'Mademoiselle',
        );

        return new \Zend\View\Model\JsonModel($etatCivil);
    }

    public function contratListAction() {
        // Changement de layout
        $this->layout('layout/ajax');

        // Table
        $typeTable = $this->getService('Table\ContratTypeTable');

        // Type Contrat
        $typeContrat = $typeTable->getList();

        return array(
            'typeContrat' => $typeContrat,
        );
    }

    public function jsonsituationlistAction() {
        // Situation
        $situation = array(
            '1' => 'Célibataire',
            '2' => 'Marié(e)',
            '3' => 'Divorcé(e)',
            '4' => 'Veuf(ve)',
        );

        return new \Zend\View\Model\JsonModel($situation);
    }

    public function saveEmployeStringDataAction() {
        // Changement de layout
        $this->layout('layout/ajax');

        // Récupération des données en Post
        $post = $this->getRequest()
                ->getPost();

        // Majuscule
        $majId = $this->params()
                ->fromRoute('id', 0);
        $maj = ($majId == 1) ? true : false;

        // Tables
        $employeTable = $this->getService('Table\EmployeTable');

        // Variables
        $pk = $post->get('pk');
        $name = $post->get('name');
        $value = $post->get('value');

        if ($maj)
            $value = strtoupper($value);

        $value = addslashes($value);

        $sql = "UPDATE rh_employe SET $name = '$value' WHERE matricule = $pk";
        $result = $employeTable->executeQuery($sql);

        return array(
            'sql' => $sql,
            'result' => $result,
        );
    }
    
    public function saveEmployeStringDataContratDateAction() {
        // Changement de layout
        $this->layout('layout/ajax');

        // Récupération des données en Post
        $post = $this->getRequest()
                ->getPost();

        // Majuscule
        $majId = $this->params()
                ->fromRoute('id', 0);
        $maj = ($majId == 1) ? true : false;

        // Tables
        $employeTable = $this->getService('Table\EmployeTable');

        // Variables
        $pk = $post->get('pk');
        $name = $post->get('name');
        $value = $post->get('value');

        if ($maj)
            $value = strtoupper($value);

        $value = addslashes($value);
        
        // employe
        $employe = $employeTable->get($pk);
        $empDebut = new RHDateTime($employe->contrat_debut); 
        $empHasFin = $employe->contrat_fin!== null && $employe->contrat_fin !== '0000-00-00' && $employe->contrat_fin !== ''; 
        $empFin = $empHasFin? new RHDateTime($employe->contrat_fin) : null;
        
        //validation
        switch ($name){
            case 'contrat_debut': 
                $newDateDebut = new RHDateTime($value);
                if( $empHasFin && $newDateDebut->isGT($empFin)) { 
                    $isValid = false;
                    $ret ['error'] = "La date d'entrée ne doit pas être ultérieure à la date de départ !" ;
                }
                else{
                    $isValid = true;
                    $ret ['success'] = 'Date entrée valide';
                }
                break;
            case 'contrat_fin':                 
                $newDateFin = new RHDateTime($value);
                if($newDateFin->isLT($empDebut)) {
                    $isValid = false;
                    $ret ['error'] = "La date de départ ne doit pas être antérieure à la date d'entrée !" ;
                } else{
                    $isValid = true;
                    $ret ['success'] = 'Date de départ valide';
                }
                break;
        }
        
        // update
        if($isValid){
              switch ($name){
                case 'contrat_debut':
                case 'contrat_fin':
                    $sql = "UPDATE rh_employe SET $name = '$value' WHERE matricule = $pk";
                    $result = $employeTable->executeQuery($sql);
                    break; 
                default:
                     $ret ['error'] = "Données invalide!";
              }
           $ret ['nouvelle_date'] = $value;
        }
        
        return new \Zend\View\Model\JsonModel( $ret );
    }

    public function saveEmployeIntDataAction() {
        // Changement de layout
        $this->layout('layout/ajax');

        // Récupération des données en Post
        $post = $this->getRequest()
                ->getPost();

        // Tables
        $employeTable = $this->getService('Table\EmployeTable');

        // Variables
        $pk = $post->get('pk');
        $name = $post->get('name');
        $value = $post->get('value');

        // Traitement des données
        if ($name == 'enfant') {
            $value = (int) $value;
            if ($value > 99) {
                $value = 0;
            }
        }

        $sql = "UPDATE rh_employe SET $name = $value WHERE matricule = $pk";
        $result = $employeTable->executeQuery($sql);

        return array(
            'sql' => $sql,
            'result' => $result,
        );
    }

    public function saveDisponibiliteIntDataAction() {
        // Changement de layout
        $this->layout('layout/ajax');

        // Table
        $disponibiliteTable = $this->getService('Table\EmployeDisponibiliteTable');

        // Données en POST
        $post = $this->getRequest()
                ->getPost();

        // Variables
        $pk = $post->get('pk');
        $name = $post->get('name');
        $value = $post->get('value');

        $sql = "UPDATE rh_employe_disponibilite SET $name = $value WHERE id = $pk";
        $result = $disponibiliteTable->executeQuery($sql);

        return array(
            'sql' => $sql,
            'result' => $result,
        );
    }

    public function saveDisponibiliteStringDataAction() {
        // Changement de layout
        $this->layout('layout/ajax');

        // Table
        $disponibiliteTable = $this->getService('Table\EmployeDisponibiliteTable');

        // Données en POST
        $post = $this->getRequest()
                ->getPost();

        // Variables
        $pk = $post->get('pk');
        $name = $post->get('name');
        $value = addslashes($post->get('value'));

        $sql = "UPDATE rh_employe_disponibilite SET $name = '$value' WHERE id = $pk";
        $result = $disponibiliteTable->executeQuery($sql);

        return array(
            'sql' => $sql,
            'result' => $result,
        );
    }

    public function saveAvenantIntDataAction() {
        // Changement de layout
        $this->layout('layout/ajax');

        // Table Avenant
        $avenantTable = $this->getService('Table\AvenantTable');

        // Données en POST
        $post = $this->getRequest()
                ->getPost();

        // Variables
        $pk = $post->get('pk');
        $name = $post->get('name');
        $value = $post->get('value');

        $sql = "UPDATE rh_avenant SET $name = $value WHERE id = $pk";
        $result = $avenantTable->executeQuery($sql);

        return array(
            'sql' => $sql,
            'result' => $result,
        );
    }

    public function saveAvenantStringDataAction() {
        // Changement de layout
        $this->layout('layout/ajax');

        // Table Avenant
        $avenantTable = $this->getService('Table\AvenantTable');

        // Données en POST
        $post = $this->getRequest()
                ->getPost();

        // Variables
        $pk = $post->get('pk');
        $name = $post->get('name');
        $value = addslashes($post->get('value'));

        $sql = "UPDATE rh_avenant SET $name = '$value' WHERE id = $pk";
        $result = $avenantTable->executeQuery($sql);

        return array(
            'sql' => $sql,
            'result' => $result,
        );
    }
    
    /* Mise à jour des date d'un avenant
     * @retrun JsonModel
     */
    
    public function saveAvenantStringDataDateAction() {
        // Changement de layout
        $this->layout('layout/ajax');

        // Table Avenant
        $avenantTable = $this->getService('Table\AvenantTable');

        // Données en POST
        $post = $this->getRequest()
                ->getPost();

        // Variables
        $pk = $post->get('pk');
        $name = $post->get('name');
        $value = addslashes($post->get('value'));

        $sql = "UPDATE rh_avenant SET $name = '$value' WHERE id = $pk";
        $result = $avenantTable->executeQuery($sql);

        $dateTime = new RHDateTime($value);
        $dataJson = array(
            'success' => true,
            'date'    => $value,
            'date_html' =>  $dateTime->date('d/m/Y')   
        );
        return new \Zend\View\Model\JsonModel($dataJson);
    }

    public function addNewAvenantAction() {
        // manager 
        $fileManager = new \RHX\Model\Manager\FileManager($this->getAdapter());
        
        
        // Changement de Layout
        $this->layout('layout/ajax');

        // Données en Post
        $post = $this->getRequest()
                ->getPost();

        // Tables
        $avenantTable = $this->getService('Table\AvenantTable');
        $avenantHistoryTable = $this->getService('Table\AvenantHistoryTable');
        $employeTable = $this->getService('Table\EmployeTable');

        // employé
        $employe = $employeTable->get($post->get('matricule'));
        $avenantOld = $employe->getAvenant();
        $debut = new RHDateTime($post->debut);
        $debut->modify('previous day');
        $avenantOld->fin = $debut->date();
        $avenantTable->save($avenantOld);

        // Nouvelle Avenant
        $avenant = new \RHX\Model\Object\Avenant($avenantTable->getAdapter(), $post);
        $avenant->site = $avenantOld->site;        
        $avenantId = $avenantTable->save($avenant);
        $avenant->id = $avenantId ;
        
        // renommer fichier de l'avenant
        $flagFile = FileManager::EMPLOYE_AVENANT_FILE;
        if($post->$flagFile != '' ){
                $fileManager->setFlag($flagFile);        
                $newName = $fileManager->renameFile(
                                            array( 'format' => array($avenant->id), 'extension' => $post[$flagFile."_extension"]),
                                            $post->$flagFile                                    
                                        );
                $avenant->$flagFile = $newName;         
            }
        $avenantTable->save($avenant);

        // Historique des Avenants
        $history = new \RHX\Model\Object\AvenantHistory($avenantHistoryTable->getAdapter());
        $history->avenant_id = $avenantId;
        $history->matricule = $post->get('matricule');
        $history->num = 1;
        $history->commentaire = date('Y-m-d') . '-' . 'Nouvel Avenant pour #' . $post->get('matricule');
        $avenantHistoryTable->save($history);

        // Mise à Jour de l'employé
        //$employe		 = $employeTable->get($post->get('matricule'));
        $employe->avenant_id = $avenantId;
        $employeTable->save($employe);

        return array(
            'post' => $post,
        );
    }
    
    /* Suppresion via ajax d'un avenant 
     */
    public function removeAvenantAction(){
        //données post
        $post = $this->getRequest()->getPost();
        
        //tables         
        $empTbl      = $this->getService('Table\EmployeTable');
        $avTbl      = $this->getService('Table\AvenantTable');
        $avHistTbl      = $this->getService('Table\AvenantHistoryTable');
        
        $idAv  = (int)$post->id;
        $matrEmp = (int)$post->id_emp;
        
        try {
            $oEmp = $empTbl->get($matrEmp);
            $oAv = $avTbl->get($idAv);
            $oAvHist = $avHistTbl->getByAvenant($idAv);
            
            // PRE SUPPRESSION
            // suprresion des l'histrorique
            $avHistTbl->erase($oAvHist->id);        
            $oAvHistLast = $avHistTbl->getLastInsertByEmploye($matrEmp);            
            
            // update employe
            $oEmp->avenant_id = $oAvHistLast->avenant_id;
            $empTbl->save($oEmp);
            
            // SUPPRESSION
            $ret = $avTbl->erase($idAv);
            
        }
        catch(\Exception $ex){
            
            return new JsonModel(array(
                'success' => false,
                'info'    => "<span>Erreur Serveur</span>",
                'debug'   => "<p>$ex</p>",
                'value'   => ''
            ));
        }
        
        return new JsonModel(array(
            'success' => true,
            'info'   => "<span>Erreur Serveur</span>",
            'debug'   => "<p>Erreur Serveur</p>",
            'value'   => ''
        ));
    }

    public function jsonpostelistAction() {
        // Table Poste
        $posteTable = $this->getService('Table\PosteTable');

        $posteList = $posteTable->getAll();
        $postes = array();
        foreach ($posteList as $p) {
            if ((int) $p->id == 0)
                continue;
            $postes[$p->id] = $p->code . ' - ' . $p->libelle;
        }

        return new \Zend\View\Model\JsonModel($postes);
    }

    /**
     * Ajouter nouvel employé
     *
     * @return array
     */
    public function addNewAction() { 
        // config
        $config = $this->getServiceLocator()->get('config');        
        $repPhoto = $config['upload_directory']['employe']['photo'];
        
        // manager 
        $fileManager = new \RHX\Model\Manager\FileManager($this->getAdapter());
        
        // Tables
        $employeTable = $this->getService('Table\EmployeTable');
        $avenantTable = $this->getService('Table\AvenantTable');
        $avenantHistory = $this->getService('Table\AvenantHistoryTable');
        $dispoTable = $this->getService('Table\EmployeDisponibiliteTable');
        $employeTemplateTable = $this->getService('Table\EmployeTemplateTable');
        $planningSemaineTable = $this->getService('Table\PlanningSemaineTable');
        $planningTemplateTable = $this->getService('Table\PlanningTemplateTable');
        $tableEntretien = new \RHX\Model\Table\EmployeEntretienTable($this->getAdapter());
        $tableSante = new \RHX\Model\Table\EmployeSanteTable($this->getAdapter());

        // Données en Post
        $post = $this->getRequest()
                ->getPost();
	$post->site = $post->site_id;
        
        // capitalize
        $post->prenom = ucwords($post->prenom);
 
        // Nouvelle Employe
        $employe = new \RHX\Model\Object\Employe($employeTable->getAdapter(), $post);

        // Nouvelle Avenant
        $avenant = new \RHX\Model\Object\Avenant($avenantTable->getAdapter(), $post);
	$avenant->site = $employe->site_id;
	$avenant->libelle = 'Contrat Initiale';

        // Sauvegarde
        $avenantId = $avenantTable->save($avenant);
        $avenant->id = $avenantId;
        $employe->avenant_id = $avenantId;
        $matricule = $employeTable->save($employe);
        $employe->matricule = $matricule;

        // Traitement des fichiers uploadés
        /* PHOTO */
        $photo = $employe->photo;
        
        /*$dirPublic = 'public/upload/photo/';
        $dir = 'upload/photo/'; */
        $dirPublic = $repPhoto;
        $dir  = str_replace('public/', '', $dirPublic) ;
        $newFile = 'photo-' .$employe->matricule . '.' . $post->photo_extension;
        
        if (@rename($dirPublic . $photo, $dirPublic . $newFile)) {
            $employe->photo = $newFile;
        } elseif (@rename($dir . $photo, $dir . $newFile)) {
            $employe->photo = $newFile;
        }
        
        // fichier joints
        $flags = array(FileManager::EMPLOYE_CV_FILE , FileManager::EMPLOYE_RIB_FILE , FileManager::EMPLOYE_CONTRAT_FILE ,  FileManager::EMPLOYE_SEJOUR_NUM_FILE );
        
        foreach ($flags as $flagFile){ 
            if($post->$flagFile != '' ){
                $fileManager->setFlag($flagFile);        
                $newName = $fileManager->renameFile(
                                            array( 'format' => array($employe->matricule), 'extension' => $post[$flagFile."_extension"]),
                                            $post->$flagFile                                    
                                        );
                $employe->$flagFile = $newName;         
            }
        }        
        // Sauvegarde des données
        $employeTable->save($employe);

        // Disponibilite
        $dispo = new \RHX\Model\Object\EmployeDisponibilite();
        $dispo->exchangeArray($post);
        $dispo->matricule = $matricule;
        $dispoTable->save($dispo);

        // Historique
        $history = new \RHX\Model\Object\AvenantHistory($avenantHistory->getAdapter());
        $history->avenant_id = $avenantId;
        $history->matricule = $matricule;
        $history->commentaire = date('Y-m-d') . ' - Embauche';
        $avenantHistory->save($history);

        // Entretien
        $entretien = new \RHX\Model\Object\EmployeEntretien();
        $entretien->matricule = $matricule;
        $entretien->date_entretien = $post->date_entretien;
        $entretien->id = $tableEntretien->save($entretien);

        // Santé
        $sante = new \RHX\Model\Object\EmployeSante();
        $sante->matricule = $matricule;
        $sante->date_visite = $post->date_visite;
        $sante->id = $tableSante->save($sante);

        // Diplomes
        $diplomes = is_array($post->diplomes) ? $post->diplomes : array();
        $tableDiplome = new \RHX\Model\Table\EmployeDiplomeTable($this->getAdapter());
        foreach ($diplomes as $d) {
            $empDiplome = new \RHX\Model\Object\EmployeDiplome($this->getAdapter());
            $empDiplome->diplome_id = $d;
            $empDiplome->matricule = $matricule;
            $tableDiplome->save($empDiplome);
        }

        // Formations
        $formations = is_array($post->formations) ? $post->formations : array();
        $tableFormation = new \RHX\Model\Table\EmployeFormationTable($this->getAdapter());
        foreach ($formations as $f) {
            $empFormation = new \RHX\Model\Object\EmployeFormation($this->getAdapter());
            $empFormation->formation_id = $f;
            $empFormation->matricule = $matricule;
            $tableFormation->save($empFormation);
        }

        // Ajout dans un planning Template s'il existe un planning type pour ce Site
        // Recherche de planning Type pour ce site
        $planningTemplates = $planningTemplateTable->getAllBySite($employe->site_id);
	
        if ($planningTemplates->count() > 0) {
            // Il y a au moins un planning type pour ce site
            // Parcours des plannings types pour insérer le nouvel employé dans tous les plannings type
            foreach ($planningTemplates as $template) {
                $employeTemplate = new \RHX\Model\Object\EmployeTemplate($employeTemplateTable->getAdapter());
                $employeTemplate->matricule = $employe->matricule;
                $employeTemplate->template = $template->template;
                // lundi
                $employeTemplate->lundi_code = $dispo->lundi;
                $employeTemplate->lundi_entree = $dispo->lundi_entree;
                $employeTemplate->lundi_sortie = $dispo->lundi_sortie;
                $data = XRules::verifyHour($dispo->lundi_entree, $dispo->lundi_sortie);
                $employeTemplate->lundi_pause = ($data['pause']) ? 1 : 0;
                $employeTemplate->lundi_repas = ($data['repas']) ? 1 : 0;
                // mardi
                $employeTemplate->mardi_code = $dispo->mardi;
                $employeTemplate->mardi_entree = $dispo->mardi_entree;
                $employeTemplate->mardi_sortie = $dispo->mardi_sortie;
                $data = XRules::verifyHour($dispo->mardi_entree, $dispo->mardi_sortie);
                $employeTemplate->mardi_pause = ($data['pause']) ? 1 : 0;
                $employeTemplate->mardi_repas = ($data['repas']) ? 1 : 0;
                // mercredi
                $employeTemplate->mercredi_code = $dispo->mercredi;
                $employeTemplate->mercredi_entree = $dispo->mercredi_entree;
                $employeTemplate->mercredi_sortie = $dispo->mercredi_sortie;
                $data = XRules::verifyHour($dispo->mercredi_entree, $dispo->mercredi_sortie);
                $employeTemplate->mercredi_pause = ($data['pause']) ? 1 : 0;
                $employeTemplate->mercredi_repas = ($data['repas']) ? 1 : 0;
                // jeudi
                $employeTemplate->jeudi_code = $dispo->jeudi;
                $employeTemplate->jeudi_entree = $dispo->jeudi_entree;
                $employeTemplate->jeudi_sortie = $dispo->jeudi_sortie;
                $data = XRules::verifyHour($dispo->jeudi_entree, $dispo->jeudi_sortie);
                $employeTemplate->jeudi_pause = ($data['pause']) ? 1 : 0;
                $employeTemplate->jeudi_repas = ($data['repas']) ? 1 : 0;
                // vendredi
                $employeTemplate->vendredi_code = $dispo->vendredi;
                $employeTemplate->vendredi_entree = $dispo->vendredi_entree;
                $employeTemplate->vendredi_sortie = $dispo->vendredi_sortie;
                $data = XRules::verifyHour($dispo->vendredi_entree, $dispo->vendredi_sortie);
                $employeTemplate->vendredi_pause = ($data['pause']) ? 1 : 0;
                $employeTemplate->vendredi_repas = ($data['repas']) ? 1 : 0;
                // samedi
                $employeTemplate->samedi_code = $dispo->samedi;
                $employeTemplate->samedi_entree = $dispo->samedi_entree;
                $employeTemplate->samedi_sortie = $dispo->samedi_sortie;
                $data = XRules::verifyHour($dispo->samedi_entree, $dispo->samedi_sortie);
                $employeTemplate->samedi_pause = ($data['pause']) ? 1 : 0;
                $employeTemplate->samedi_repas = ($data['repas']) ? 1 : 0;
                // dimanche
                $employeTemplate->dimanche_code = $dispo->dimanche;
                $employeTemplate->dimanche_entree = $dispo->dimanche_entree;
                $employeTemplate->dimanche_sortie = $dispo->dimanche_sortie;
                $data = XRules::verifyHour($dispo->dimanche_entree, $dispo->dimanche_sortie);
                $employeTemplate->dimanche_pause = ($data['pause']) ? 1 : 0;
                $employeTemplate->dimanche_repas = ($data['repas']) ? 1 : 0;

                // Version
                $version = $template->getVersion();
                $employeTemplate->version = '';
                for ($i = 0; $i < $version; $i++) {
                    $employeTemplate->version .= '0';
                }
                $employeTemplate->version .= '1';
                // Sauvegarde des données
                print('id enreg : ' .$employeTemplateTable->save($employeTemplate));

                // Mise à jour des anciens template pour une update de la version
                $template->addVersion();
                // On met à jour le planning semaine future correspondant au planning type
                //$planningSemaineTable->hire($matricule, $template->template);
                $date = $employe->contrat_debut;
                $date = ($date == '0000-00-00') ? date('Y-m-d') : $date;
                //$this->hire($matricule, $date);
		
		/* bug =>commented
		 * desc: crée une seconde ligne "template employe"
		    // template manager
		    $templateManager = new \RHX\Model\Manager\TemplateManager($this->getAdapter());
		    $templateManager->updateAllTemplate();
		 * 
		 */
		 
            }
        }
	
	//Ajout de planning semaine  s'il en existe	
	$this->createNewPlanningSemaine ($employe);
	
        return $this->redirect()
                        ->toRoute('RHX/default', array('controller' => 'employe', 'action' => 'index', 'id' => $employe->site_id, 'other1' => 1));

//	return array(
//	    'post'		 => $post,
//	    'employe'	 => $employe,
//	    'avenant'	 => $avenant,
//	    'history'	 => $history,
//	);
    }
    
    /* creation eventuelle d'un planning semaine pour un user existant
     * @param \RHX\Model\Object\Employe $employe
     */
    public function createNewPlanningSemaine ($employe = null)
	{
            $manager = new \RHX\Model\Manager\EmployeManager($this->getAdapter());
            //tbl
	    $periodeTable		 = $this->getService('Table\PeriodeTable');
	    $periodeSemaineTable	 = $this->getService('Table\PeriodeSemaineTable');
	    $psTbl 	 = $this->getService('Table\PlanningSemaineTable'); 	    
	    $employeTemplateTbl = $this->getService('Table\EmployeTemplateTable');
	    $dispoTbl = $this->getService('Table\EmployeDisponibiliteTable');
            
            //view
            $planningListView = $this->getService('View\PSPlanningView');
	    $periodes = $periodeTable->getAll('id DESC');
	    
	    $dispo = $dispoTbl->getDispoByEmploye($employe->matricule);
	    
	    
	    foreach ($periodes as $periode) :		    
		$bChevauche = $manager->chevauchePeriodeEmploye($employe->matricule, $periode->id );
		$semaineList = $periodeSemaineTable->getSemainesByPeriode($periode->id, 'id desc');

		printf("periode : %d <hr>", $periode->id);

		echo $bChevauche? 'chPrd' : 'notchPrd' ;
		if($bChevauche){
		    $dayWks			 = array('lundi', 'mardi', 'mercredi', 'jeudi', 'vendredi', 'samedi', 'dimanche');

		    foreach ($semaineList as $semaine) : 
			    $lundi		 = $semaine->lundi;
			    printf("<br>semaine %s : ", $lundi);

			    $prdSemPlanningView	 = $planningListView->getOne($periode->id, $semaine->id, $employe->site_id);
			    $templateId		 = (int) $prdSemPlanningView->template;
			    $hasTemplateApplied = $templateId ? true : false;
			    printf("%s <br>", $hasTemplateApplied ? "has tpl": "hasnt tpl");
			    //$employeTemplate	 = $employeTemplateTbl->getEmployeTemplate($employe->matricule, $templateId);
			    if($hasTemplateApplied){
				$planning = new \RHX\Model\Object\PlanningSemaine($psTbl->getAdapter());
				echo "<table><tr><td width='10%'>L</td><td>M</td><td>M</td><td>J</td><td>V</td><td>S</td><td>D</td></tr>";
				echo "<tr>";
				foreach ($dayWks as $i => $daywk){	
				    echo('<td>');
				    $day = strtolower($daywk);

				    $dayCode	 = $day . '_code';
				    $dayEntree	 = $day . '_entree';
				    $daySortie	 = $day . '_sortie';
				    $dayPause	 = $day . '_pause';
				    $dayRepas	 = $day . '_repas';

				    $planning->$day = $semaine->$day;

				    $isDayInContrat = $employe->isDayInContrat($planning->$day);
				    print($isDayInContrat ? "<span style='color: blue;'>in </span>" : "<span style='color: red;'>nt</span>");

				    if ($isDayInContrat) {
					//si jour est entre la date d'entrée et de sortie et si, éventuellement, pas de date de depart => CODE TEMPLATE</pre>";                               
					/*$planning->$dayCode	 = $employeTemplate->$dayCode;
					$planning->$dayEntree	 = $employeTemplate->$dayEntree;
					$planning->$daySortie	 = $employeTemplate->$daySortie;
					$planning->$dayPause	 = $employeTemplate->$dayPause;
					$planning->$dayRepas	 = $employeTemplate->$dayRepas;*/

					$planning->$dayCode	 = $dispo->$day ;
					$planning->$dayEntree	 = $dispo->$dayEntree;
					$planning->$daySortie	 = $dispo->$daySortie;
					$planning->$dayPause	 = 0;
					$planning->$dayRepas	 = 0;					
				    }
				    else {
					$planning->$dayCode	 = XRules::EntreeSortie;
					$planning->$dayEntree	 = "00:00";
					$planning->$daySortie	 = "00:00";
					$planning->$dayPause	 = 0;
					$planning->$dayRepas	 = 0;
				    }

				    print("<span style='color: blue;'>".$planning->$dayCode."</span>");
				    echo('</td>');
				}
				$planning->matricule	 = $employe->matricule;
				//var_dump($planning);
				$psTbl->save($planning);
			    }
			    echo "<tr>";
			    echo "</table>";
		    endforeach;
		}
		else{

		}
	    endforeach;	    
	}
	

      /* determine si un employe donnée empiete une periode donné
       * @param int $employeId matricule d'un employé
       * @param int $periodeId ID d'un periode
       * @return boolean
       */
      public function chevauchePeriodeEmploye($employeMatr , $periodeId){
	$periodeTbl		 = $this->getService('Table\PeriodeTable');
	$employeTable		 = $this->getService('Table\EmployeTable');
	  
	$employe = $employeTable->get($employeMatr);
	$periode = $periodeTbl->get($periodeId);	
	  
	$dateEntree	 = new RHDateTime($employe->contrat_debut);
	$hasDateDepart	 = $employe->contrat_fin != null && $employe->contrat_fin !== '' && $employe->contrat_fin !== '0000-00-00';
	$dateDepart	 = $hasDateDepart ? new RHDateTime($employe->contrat_fin) : null;
		  
	$periodeDebut	 = new RHDateTime($periode->debut);
	$periodeFin	 = new RHDateTime($periode->fin);

	if ($dateEntree->isGT($periodeFin)) { ////echo"  dateEntree > periodeFin <br>" ;
	    $isChevauchePrd = FALSE;
	}
	else {
	    if ($dateEntree->isBetween($periodeDebut, $periodeFin)) // dateEntree between (periodeDebut periodeFin
		$isChevauchePrd = TRUE;
	    else { //  $dateEntree < $periodeDebut
		if (!$hasDateDepart)
		    $isChevauchePrd	 = TRUE;
		else
		    $isChevauchePrd	 = ($dateDepart->isLT($periodeDebut) ) ? FALSE : TRUE;
	    }
	}
	
	return $isChevauchePrd;
      }


    public function avenantAction() {
        // Changement de layout
        $this->layout('layout/ajax');

        // Variable
        $matricule = $this->params()->fromRoute('id', 0);

        $history = array();

        // Table
        $historyTable = $this->getService('Table\AvenantHistoryTable');

        // Liste
        $historyList = $historyTable->getByMatricule($matricule);
        //var_dump($historyList);
        // Parcours de la liste
        foreach ($historyList as $h) {
            //var_dump($h);
            $avenant = $h->getAvenant();
            //var_dump($avenant);
            $employe = $h->getEmploye();
            $poste = $avenant->getPoste();

            $data['avenant'] = $avenant;
            $data['employe'] = $employe;
            $data['poste'] = $poste;

            $history[] = $data;
        }

        return array(
            //'list' => $list,
            'stories' => $history,
        );
    }

    public function avenantdetailsAction() {
        // Changement de layout
        $this->layout('layout/ajax');

        // Données en Post
        $post = $this->getRequest()->getPost();

        // Avenant ID
        $id = (int) $this->params()->fromRoute('id', 0);

        // table
        $avenantTable = $this->getService('Table\AvenantTable');

        // Avenant
        $avenant = $avenantTable->get($id);
        $poste = $avenant->getPoste();

        return array(
            'avenant' => $avenant,
            'poste' => $poste,
            'title' => $post->get('title'),
        );
    }

    public function jsontransportlistAction() {
        // Table
        $transportTable = $this->getService('Table\TransportTable');

        $transportList = $transportTable->getSelectList();

        return new \Zend\View\Model\JsonModel($transportList);
    }

    public function jsonMotifListAction() {
        // Table
        $motifTable = $this->getService('Table\MotifTable');

        $motifList = $motifTable->getList();

        return new \Zend\View\Model\JsonModel($motifList);
    }

    public function jsonPosteDataAction() {
        // Table
        $posteTable = $this->getService('Table\PosteTable');

        // Paramètres
        $posteId = $this->params()
                ->fromRoute('id', 0);

        // Poste
        $poste = $posteTable->get($posteId);
        $poste->niveau = Number::getRomanNumber($poste->niveau);
        $poste->echelon = Number::getRomanNumber($poste->echelon);

        return new \Zend\View\Model\JsonModel($poste->getArrayCopy());
    }

    public function selectDiplomeAction() {
        // Changement de layout
        $this->layout('layout/ajax');

        // Table
        $diplomeTable = new \RHX\Model\Table\DiplomeTable($this->getAdapter());

        // POST
        $post = $this->getRequest()
                ->getPost();

        // Tous les diplomes
        $diplomes = $diplomeTable->getAll();

        return array(
            'count' => $diplomes->count(),
            'diplomes' => $diplomes,
            'matricule' => $post->matricule,
        );
    }

    public function selectFormationAction() {
        // Changement de layout
        $this->layout('layout/ajax');

        // Table
        $formationTable = new \RHX\Model\Table\FormationTable($this->getAdapter());

        // POST
        $post = $this->getRequest()
                ->getPost();

        // Tous les formations
        $formations = $formationTable->getAll();

        return array(
            'count' => $formations->count(),
            'formations' => $formations,
            'matricule' => $post->matricule,
        );
    }

    public function addDiplomeAction() {
        //$this->layout('layout/ajax');
        $employeTable = $this->getService('Table\EmployeTable');
        $adapter = $employeTable->getAdapter();
        $employeDiplomeTable = new \RHX\Model\Table\EmployeDiplomeTable($adapter);

        $empDip = new \RHX\Model\Object\EmployeDiplome($adapter);

        // POST
        $post = $this->getRequest()
                ->getPost();
        $empDip->matricule = $post->matricule;
        $empDip->diplome_id = $post->diplome;
        $empDip->remarque = date('Y-m-d');
        $id = 100000000;
        if ((int) $post->diplome != 0) {
            $id = $employeDiplomeTable->save($empDip);
            $empDip->id = $id;
        }

        $result = array(
            'etat' => ($id > 0) ? true : false,
            'employeDiplome' => $empDip,
            'diplome' => $empDip->getDiplome(),
        );

        return new JsonModel($result);
    }

    public function addFormationAction() {
        $employeFormationTable = new \RHX\Model\Table\EmployeFormationTable($this->getAdapter());

        // POST
        $post = $this->getRequest()
                ->getPost();

        // Nouveau
        $empForm = new \RHX\Model\Object\EmployeFormation($this->getAdapter());
        $empForm->matricule = $post->matricule;
        $empForm->formation_id = $post->formation;
        $empForm->remarque = date('Y-m-d');
        $id = $employeFormationTable->save($empForm);
        $empForm->id = $id;

        $result = array(
            'etat' => ($id > 0) ? true : false,
            'employeFormation' => $empForm,
            'formation' => $empForm->getFormation(),
        );

        return new JsonModel($result);
    }

    /**
     * Liste des mutuelles
     * 
     * @return \Zend\View\Model\JsonModel
     */
    public function mutuelleListAction() {
        // Table Mutuelle
        $mutuelleTable = new \RHX\Model\Table\MutuelleTable($this->getAdapter());

        // Mutuelles
        $mutuelles = $mutuelleTable->select(function(\Zend\Db\Sql\Select $select) {
            $select->order('id DESC');
        });
        $json = array();
        // Parcours des mutuelles
        foreach ($mutuelles as $m) {
            $json[$m->id] = $m->libelle;
        }

        return new JsonModel($json);
    }

    /**
     * Liste des Mutuelles
     * 
     * @return \Zend\View\Model\JsonModel
     */
    public function sejourListAction() {
        // Table Mutuelle
        $sejourTable = new \RHX\Model\Table\TitreSejourTable($this->getAdapter());

        // Mutuelles
        $sejours = $sejourTable->select(function(\Zend\Db\Sql\Select $select) {
            $select->order('id DESC');
        });
        $json = array();
        // Parcours des mutuelles
        foreach ($sejours as $s) {
            $json[$s->id] = $s->libelle;
        }

        return new JsonModel($json);
    }

    public function saveEmployeSanteDataAction() {
        // Table Sante
        $santeTable = new \RHX\Model\Table\EmployeSanteTable($this->getAdapter());

        // POST
        $post = $this->getRequest()
                ->getPost();
        // Variables
        $pk = $post->pk;
        $name = $post->name;
        $value = $post->value;

        // Santé en cours
        $sante = $santeTable->get($pk);
        $sante->date_visite = $value;
        $sante->id = 0;

        // Sauvegarder nouveau
        $id = $santeTable->save($sante);

        return new JsonModel(array(
            'id' => $id,
            'sante' => $sante,
        ));
    }

    public function saveEmployeEntretienDataAction() {
        // Table entretien
        $tableEntretien = new \RHX\Model\Table\EmployeEntretienTable($this->getAdapter());

        // POST
        $post = $this->getRequest()
                ->getPost();
        // Variables
        $pk = $post->pk;
        $value = $post->value;

        // Entretien en cours
        $entretien = $tableEntretien->get($pk);
        $entretien->date_entretien = $value;
        $entretien->id = 0;

        // Sauvegarde
        $id = $tableEntretien->save($entretien);

        return new JsonModel(array(
            'id' => $id,
            'entretien' => $entretien,
        ));
    }

    /**
     *
     * @return array
     */
    public function uploadFileFormAction() {
        // Changement de layout
        $this->layout('layout/iframe');

        // Paramètre Route
        $mat = $this->params()
                ->fromRoute('id', 0);

        $form = new \RHX\Form\UploadFileForm('uploadFile');
        $matricule = $form->get('matricule');
        $matricule->setValue($mat);

        return array(
            'form' => $form,
            'matricule' => $mat,
        );
    }

    public function uploadFileOldAction() {
        $this->layout('layout/iframe2');
        $form = new \RHX\Form\UploadFileForm('uploadFile');
        // Request
        $request = $this->getRequest();
        if ($request->isPost()) {
            //echo "POST\n";
            $post = array_merge_recursive(
                    $request->getPost()->toArray(), $request->getFiles()->toArray()
            );
            $form->setData($post);
            if ($form->isValid()) {
                //echo "VALIDE\n";
                $data = $form->getData();
                //var_dump($data);
                //echo getcwd();
                // Changement de répertoire
                $tmpName = $data['filepath']['tmp_name'];
                $matricule = $data['matricule'];
                $name = "cv-$matricule.pdf";
                $destination = "/module/RHX/data/pdf/$name";
                $result = move_uploaded_file($tmpName, getcwd() . $destination);
                if ($result) {
                    // Sauvegarde dans la base de données
                    $tableEmploye = new \RHX\Model\Table\EmployeTable($this->getAdapter());
                    $employe = $tableEmploye->get($matricule);
                    $employe->cv_path = $destination;
                    $tableEmploye->save($employe);
                }

                return array(
                    'data' => $data,
                    'result' => $result,
                    'form' => $form,
                );
            } else {
                $fileErrors = $form->get('filepath')->getMessages();
                if (empty($fileErrors)) {
                    $tempFile = $form->get('filepath')->getValue();
                }
            }
        }

        return array(
            'data' => null,
            'form' => $form,
        );
    }

    public function dialogUploadAction() {
        $this->layout('layout/ajax');

        // Paramètre Route
        $matricule = $this->getRequest()
                ->getPost()
                ->get('matricule');

        return array(
            'matricule' => $matricule,
        );
    }

    /**
     * Sauvegarde d'un CV employé
     * 
     * @return array
     */
    public function saveCvEmployeAction() {
        // POST
        $post = $this->getRequest()
                ->getPost();
        $matricule = $post->matricule;

        $destination_path = getcwd() . "/public/upload/cv/";

        $result = 0;

        //$target_path = $destination_path . basename($_FILES['myfile']['name']);
        $target_path = $destination_path . "$matricule.pdf";

        if (@move_uploaded_file($_FILES['myfile']['tmp_name'], $target_path)) {
            $result = 1;
        }

        /*
         * Enregistrement dans la base de données
         */
        if ($result == 1) {
            // Table Employe
            $tableEmploye = new \RHX\Model\Table\EmployeTable($this->getAdapter());
            $employe = $tableEmploye->get($matricule);
            $employe->cv_path = "/upload/cv/$matricule.pdf";
            $tableEmploye->save($employe);
        }

        sleep(1);

        return array('result' => $result);
    }

    public function cancelDateAction() {
        // changement de layout
        $this->layout('layout/ajax');
        $post = $this->getRequest()
                ->getPost();
        // adapter
        $adapter = $this->getAdapter();
        // requete
        $pk = $post->pk;
        $name = $post->name;
        $value = addslashes($post->value);
        $id = $post->id;
        $sql = '';
        if ($post->table == 'undefined') {
            $sql = "UPDATE rh_employe SET $name = '$value' WHERE matricule = $pk";
        } else {
            $table = $post->table;
            $sql = "UPDATE $table SET $name = '$value' WHERE id = $pk";
        }
        $r = $adapter->query($sql)
                ->execute();
//	$r	 = false;
//	$done	 = true;
        if ($r) {
            $done = true;
        }

        return new JsonModel(array(
            'done' => $done,
            'post' => $post,
            'sql' => $sql,
        ));
    }

    /**
     * Liste des types de contrats
     * 
     * @return \Zend\View\Model\JsonModel
     */
    public function contratTypeListAction() {
        $tableContratType = new \RHX\Model\Table\ContratTypeTable($this->getAdapter());
        $list = $tableContratType->getAll('libelle DESC');
        $array = array();
        foreach ($list as $t) {
            if ((int) $t->id == 0)
                continnue;
            $array[$t->id] = $t->libelle;
        }

        return new JsonModel($array);
    }

    /**
     * Embauche
     * 
     * @param int $matricule
     * @param int $template
     */
    public function hire_($matricule, $date) {
        try {
            //Debug::dump($matricule, 'Matricule');
            //Debug::dump($date, 'Date');
            // table période
            $tablePeriode = new \RHX\Model\Table\PeriodeTable($this->getAdapter());
            $data = $tablePeriode->getPeriodeByDate($date, false);
            $periode = new \RHX\Model\Object\Periode($data);
            //Debug::dump($periode, "Periodes");
            // table employé
            $tableEmploye = new \RHX\Model\Table\EmployeTable($this->getAdapter());
            $employe = $tableEmploye->get($matricule);
            $dispo = $employe->getDisponibilite();

            // table periode semaine
            $tablePeriodeSemaine = new \RHX\Model\Table\PeriodeSemaineTable($this->getAdapter());
            $semaines = $tablePeriodeSemaine->getSemainesByPeriode($periode->id);
            //Debug::dump($semaines, "Semaines");
            // tabe planning
            $tablePlanning = new \RHX\Model\Table\PlanningSemaineTable($this->getAdapter());

            // variables
            $daysOfWeek = array(
                'lundi', 'mardi', 'mercredi', 'jeudi', 'vendredi', 'samedi', 'dimanche',
            );
            $code = 0;
            $entree = '00:00';
            $sortie = '00:00';

            // Mise à jour des plannings semaines de l'employe
            // pour la période en cours
            // avant l'embauche ; c'est un code entrée/sortie
            echo "<pre>Parcours de la liste des semaines de la périodes</pre>";
            foreach ($semaines as $semaine) {
                //Debug::dump($semaine, 'Semaine');
                $planning = new \RHX\Model\Object\PlanningSemaine($this->getAdapter());
                $days = array(
                    $semaine->lundi, $semaine->mardi, $semaine->mercredi, $semaine->jeudi, $semaine->vendredi, $semaine->samedi, $semaine->dimanche,
                );
                echo "<pre>Analyse de la date</pre>";
                if ($semaine->isIn($date)) {
                    // La date appartient à la semaine en cours
                    echo "<pre>La date appartient à la semaine en cours</pre>";
                    $index = array_search($date, $days);
                    //Debug::dump($index, 'Position d\'index');
                    if ($index === FALSE) {
                        // Introuvable
                        echo "<pre>Introuvable</pre>";
                        //Debug::dump($index, "Index");
                        throw new \Exception("La date n'a pas été trouvée, alors qu'elle est sensée être présente");
                    } else {
                        // Il y a une concordance
                        echo "<pre>Il y a une concordance</pre>";
                        //Debug::dump($index, "Index");
                        for ($i = 0; $i < 7; $i++) {
                            $day = $daysOfWeek[$i];
                            $dayCode = $day . '_code';
                            $dayEntree = $day . '_entree';
                            $daySortie = $day . '_sortie';
                            $dayPause = $day . '_pause';
                            $dayRepas = $day . '_repas';
                            if ($i <= $index) {
                                // CODE ES
                                echo "<pre>CODE ES</pre>";
                                //Debug::dump($index, "Index");
                                $code = XRules::EntreeSortie;
                            } else {
                                // CODE Dispo
                                echo "<pre>CODE Dispo</pre>";
                                //Debug::dump($index, "Index");
                                $code = $dispo->$day;
                                $entree = $dispo->$dayEntree;
                                $sortie = $dispo->$daySortie;
                            }
                            // Assignation
                            $planning->$day = $semaine->$day;
                            $planning->$dayCode = $code;
                            $planning->$dayEntree = $entree;
                            $planning->$daySortie = $sortie;
                            $result = XRules::verifyHour($entree, $sortie);
                            $planning->$dayPause = ($result['pause']) ? 1 : 0;
                            $planning->$dayRepas = ($result['repas']) ? 1 : 0;
                        }
                    }
                } else {
                    // La date n'appartient pas à la semaine en cours
                    echo "<pre>La date n'appartient pas à la semaine en cours</pre>";
                    //Debug::dump($date, 'Date');
                    $date = new RHDateTime($date);
                    $lundi = new RHDateTime($semaine->lundi);
                    $dimanche = new RHDateTime($semaine->dimanche);
                    if ($date->isGT($dimanche)) {
                        // la date appartient à une date ultérieur aux dates de la semaine
                        // toutes les dates sont en Code ES
                        echo "<pre>La date appartient à une date ultérieur aux dates de la semaine<br>toutes les dates sont en Code ES</pre>";
                        for ($i = 0; $i < 7; $i++) {
                            $day = $daysOfWeek[$i];
                            $dayCode = $day . '_code';
                            $dayEntree = $day . '_entree';
                            $daySortie = $day . '_sortie';
                            $dayPause = $day . '_pause';
                            $dayRepas = $day . '_repas';
                            // assignation
                            $planning->$day = $semaine->$day;
                            $planning->$dayCode = XRules::EntreeSortie;
                            $planning->$dayEntree = '00:00';
                            $planning->$daySortie = '00:00';
                            $planning->$dayPause = 0;
                            $planning->$dayRepas = 0;
                        }
                    } elseif ($date->isLT($lundi)) {
                        // la date appartient à une date postérieur aux dates de la semaine
                        // toutes les dates sont en code de la disponibilité
                        echo "<pre>la date appartient à une date postérieur aux dates de la semaine<br>toutes les dates sont en code de la disponibilité</pre>";
                        for ($i = 0; $i < 7; $i++) {
                            $day = $daysOfWeek[$i];
                            $dayCode = $day . '_code';
                            $dayEntree = $day . '_entree';
                            $daySortie = $day . '_sortie';
                            $dayPause = $day . '_pause';
                            $dayRepas = $day . '_repas';
                            // assignation
                            $planning->$day = $semaine->$day;
                            $planning->$dayCode = $dispo->$day;
                            $planning->$dayEntree = $dispo->$dayEntree;
                            $planning->$daySortie = $dispo->$daySortie;
                            $result = XRules::verifyHour($dispo->$dayEntree, $dispo->$daySortie);
                            $planning->$dayPause = ($result['pause']) ? 1 : 0;
                            $planning->$dayRepas = ($result['repas']) ? 1 : 0;
                        }
                    }
                }
                // sauvegarde
                $planning->matricule = $matricule;
                $planning->id = $tablePlanning->save($planning);
                //Debug::dump($planning, "Planning");
            }
            // Pour les semaines futures
            // Il faut sélectionner les plannings du site supérieur à date de fin de période
            $plannings = $tablePlanning->getPlanningByDay($periode->fin, $employe->site_id);
            //Debug::dump($plannings, "Listes des plannings");
            foreach ($plannings as $pl) {
                $planning = new \RHX\Model\Object\PlanningSemaine($this->getAdapter());
                for ($i = 0; $i < 7; $i++) {
                    $day = $daysOfWeek[$i];
                    $dayCode = $day . '_code';
                    $dayEntree = $day . '_entree';
                    $daySortie = $day . '_sortie';
                    $dayPause = $day . '_pause';
                    $dayRepas = $day . '_repas';
                    // assignation
                    $planning->$day = $pl->$day;
                    $planning->$dayCode = XRules::EntreeSortie;
                    $planning->$dayEntree = '00:00';
                    $planning->$daySortie = '00:00';
                    $planning->$dayPause = 0;
                    $planning->$dayRepas = 0;
                }
                $planning->matricule = $matricule;
                $planning->id = $tablePlanning->save($planning);
                //Debug::dump($pl, "Planning Copy");
                //Debug::dump($planning, "Planning");
            }
        } catch (\Exception $ex) {
            $this->redirect()
                    ->toRoute('RHX/default', array('controller' => 'employe'));
        }
    }

    /**
     * Licenciement
     * 
     * @param int $matricule
     * @param string $date
     */
    public function fire($matricule, $date) {
        // table employé
        $tableEmploye = new \RHX\Model\Table\EmployeTable(($this->getAdapter()));
        try {
            $employe = $tableEmploye->get($matricule);
        } catch (\Exception $ex) {
            throw new \Exception("L'employé au matricule '$matricule' est introuvable!");
        }
        $employe->actif = 0;
        $employe->contrat_fin = $date;
        // sauvegarde des données de l'employé
        $tableEmploye->save($employe);

        // Mise à jour des plannings types
	$templateManager = new \RHX\Model\Manager\TemplateManager($this->getAdapter());
	$templateManager->updateAllTemplate();
//        $tablePlanningTemplate = new \RHX\Model\Table\PlanningTemplateTable($this->getAdapter());
//        $planningTemplates = $tablePlanningTemplate->getAllBySite($employe->site_id);
//        foreach ($planningTemplates as $template) {
//            $template->addVersion();
//        }
//        // Mise à jour des plannings types de l'employé
//        $templates = $employe->getTemplates();
//        $tableEmployeTemplate = new \RHX\Model\Table\EmployeTemplateTable($this->getAdapter());
//        foreach ($templates as $template) {
//            $version = $template->version;
//            $prefix = substr($version, 0, strlen($version) - 1);
//            $newVersion = $prefix . '0';
//            $template->version = $newVersion;
//            $tableEmployeTemplate->save($template);
//        }
//        // Mise à jour des plannings semaine dans la période en cours
//        $tablePlanning = new \RHX\Model\Table\PlanningSemaineTable($this->getAdapter());
//        $tablePeriode = new \RHX\Model\Table\PeriodeTable($this->getAdapter());
//        $periode = $tablePeriode->getPeriodeByDate($date);
//        $plannings = $tablePlanning->getPlanningByPeriode($periode, $employe->matricule);
//        $days = array(
//            'lundi', 'mardi', 'mercredi', 'jeudi', 'vendredi', 'samedi', 'dimanche',
//        );
//        $refDate = new RHDateTime($date);
//        foreach ($plannings as $planning) {
//            // Analyse de la date
//            $edited = false;
//            for ($i = 0; $i < 7; $i++) {
//                $day = $days[$i];
//                $dayCode = $day . '_code';
//                $dayEntree = $day . '_entree';
//                $daySortie = $day . '_sortie';
//                $dayPause = $day . '_pause';
//                $dayRepas = $day . '_repas';
//
//                $refDay = new RHDateTime($planning->$day);
//                if ($refDay->isGT($refDate)) {
//                    $planning->$dayCode = XRules::EntreeSortie;
//                    $planning->$dayEntree = '00:00';
//                    $planning->$daySortie = '00:00';
//                    $planning->$dayPause = 0;
//                    $planning->$dayRepas = 0;
//                    $edited = true;
//                }
//            }
//            if ($edited) {
//                $tablePlanning->save($planning);
//            }
//        }
//        // Plannings Future de l'employé
//        $nextDay = new RHDateTime($periode->fin);
//        $nextDay->modify('next day');
//        $plannings = $tablePlanning->getPlanningsByDate($nextDay->date(), $employe->site_id);
//        foreach ($plannings as $planning) {
//            if ($planning->matricule == $employe->matricule) {
//                //$tablePlanningTemplate->erase($planning->id);
//            }
//        }
    }

    public function contratAddAction() {
        // changement de layout
        $this->layout('layout/ajax');
        // table employe
        $tableEmploye = new \RHX\Model\Table\EmployeTable($this->getAdapter());
        // post
        $post = $this->getRequest()
                ->getPost();

        // employe
        try {
            $employe = $tableEmploye->get($post->matricule);
            $old = clone $employe;
            $old->actif = 0;
            $old->matricule = 0;
            $finOld = new RHDateTime($post->contrat_debut);
            $finOld->modify('previous days');
            $old->contrat_fin = $finOld->date();
            $old->contrat_motif_depart = $post->contrat_motif;
            $avenantOld = $old->getAvenant();
            $avenantOld->fin = $old->contrat_fin;
            // Enregistrement des anciennes informations
            $old->matricule = $tableEmploye->save($old);
            
	    // Renommer fichier	    
	    $fileManager = new FileManager($this->getAdapter());
	    $fileManager->setFlag(FileManager::EMPLOYE_CONTRAT_FILE);
	    
	    //$uploadDir = $fileManager->getUploadDirectory();
	    $newName = $fileManager->renameFile(array('format' => array($old->matricule), 'extension' => 'pdf'), $old->contrat_file);
	    $old->contrat_file = $newName;
	    $tableEmploye->save($old);
	    $employe->contrat_file = '';
	    $tableEmploye->save($employe);

            // Nouvelles informations
            $employe->actif = 1;
            $employe->ancien = $old->matricule;
            $employe->indice++;
            $employe->contrat_debut = $post->contrat_debut;
            $employe->contrat_fin = $post->contrat_fin;
            $employe->contrat_motif_depart = $post->contrat_motif;
            $employe->contrat_type = (int) $post->contrat_type;
            // Avenant
            $tableAvenant = new \RHX\Model\Table\AvenantTable($this->getAdapter());
            $avenant = new \RHX\Model\Object\Avenant($this->getAdapter());
            $avenant->debut = $post->contrat_debut;
            $avenant->fin = '0000-00-00';
            $avenant->hebdo = $post->hebdo;
            $avenant->taux = $post->taux;
            $avenant->poste_id = $post->poste;
            $avenant->college = $post->college;
            $avenant->niveau = $post->niveau;
            $avenant->echelon = $post->echelon;
	    $avenant->site = $employe->site_id;
            $avenant->id = $tableAvenant->save($avenant);
	    $avenant->libelle = 'Nouveau Contrat';
            $employe->avenant_id = $avenant->id;
            $tableEmploye->save($employe);
            // Historique des anciens avenants
            $tableHistory = new \RHX\Model\Table\AvenantHistoryTable($this->getAdapter());
            $tableHistory->updateHistoryMatricule($employe->matricule, $old->matricule);
            $history = new \RHX\Model\Object\AvenantHistory($this->getAdapter());
            $history->matricule = $employe->matricule;
            $history->avenant_id = $avenant->id;
            $history->commentaire = date('Y-m-d') . "-Ajout Contrat pour #{$employe->matricule}- Ancien Matricule #{$employe->ancien} - Contrat #{$employe->indice}";
            $tableHistory->save($history);
        } catch (\Exception $ex) {
            return array(
                'exception' => $ex,
                'post' => $post,
            );
        }

        return array(
            'employe' => $employe,
            'old' => $old,
            'avenant' => $avenant,
            'history' => $history,
            'post' => $post,
        );
    }

    public function showContratMenuAction() {
        // changement de layout
        $this->layout('layout/ajax');
        // post
        $post = $this->getRequest()
                ->getPost();
        // table employe
        $tableEmploye = new \RHX\Model\Table\EmployeTable($this->getAdapter());
        // employe
        try {
            $employe = $tableEmploye->get($post->matricule);
            // test des données
            //$dateEtat	 = '1-Erreur';
            $dateEtat = '0';
            $contratFin = new RHDateTime('now');
            if ($employe->contrat_fin != '0000-00-00') {
                $contratFin = new RHDateTime($employe->contrat_fin);
                $now = new RHDateTime();
                if ($contratFin->isGT($now)) {
                    //$dateEtat = '2-La date de fin de contrat est supérieure à la date en cours';
                } else {
                    //$dateEtat = '0';
                }
            } else {
                //$dateEtat = '1-La date de fin de contrat est vide';
            }
            return array(
                'employe' => $employe,
                'etat' => $dateEtat,
            );
        } catch (\Exception $ex) {
            return array('exception' => $ex);
        }
    }

    /**
     * Liste des collèges
     * 
     * @return \Zend\View\Model\JsonModel
     */
    public function collegeListAction() {
        // changement de layout
        $this->layout('layout/ajax');
        // table college
        $tableCollege = new \RHX\Model\Table\CollegeTable($this->getAdapter());
        $colleges = $tableCollege->getAll("id DESC");
        $collegeArray = array();
        foreach ($colleges as $college) {
            $collegeArray[$college->id] = $college->libelle;
        }

        return new JsonModel($collegeArray);
    }

    /**
     * Liste des nationalités
     * 
     * @return \Zend\View\Model\JsonModel
     */
    public function getNationaliteListAction() {
        $tableNationalite = new \RHX\Model\Table\NationaliteTable($this->getAdapter());
        $nationalites = $tableNationalite->getAll("id DESC");
        $nations = array();
        foreach ($nationalites as $n) {
            $nations[$n->id] = ucfirst($n->libelle);
        }

        return new JsonModel($nations);
    }

    /**
     * Information sur le poste
     * 
     * @return \Zend\View\Model\JsonModel
     */
    public function getPosteInfoAction() {
        $tablePoste = new \RHX\Model\Table\PosteTable($this->getAdapter());
        $post = $this->getRequest()
                ->getPost();
        try {
            $poste = $tablePoste->get($post->id);
        } catch (\Exception $ex) {
            $poste = new \RHX\Model\Object\Poste();
        }
        $return = array();
        $return['id'] = (int) $poste->id;
        $return['libelle'] = $poste->libelle;
        $return['niveau'] = 'Niveau ' . Number::getRomanNumber($poste->niveau);
        $return['niveau_value'] = (int) $poste->niveau;
        $return['echelon'] = 'Echelon ' . ($poste->echelon);
        $return['echelon_value'] = (int) $poste->echelon;
        $tableCollege = new \RHX\Model\Table\CollegeTable($this->getAdapter());
        try {
            $college = $tableCollege->get($poste->college);
        } catch (\Exception $ex) {
            $college = new \RHX\Model\Object\College();
            $college->id = 1;
            $college->libelle = "Employé";
        }
        $return['college'] = $college->libelle;
        $return['college_value'] = (int) $college->id;

        return new JsonModel(array(
            'info' => $return,
        ));
    }

    /**
     * Information sur l'employé
     *
     * @return \Zend\View\Model\JsonModel
     */
    public function getEmployeInfoAction() {
        $post = $this->getRequest()
                ->getPost();
        $tableEmploye = new \RHX\Model\Table\EmployeTable($this->getAdapter());
        $employe = $tableEmploye->get($post->matricule);

        return new JsonModel(array(
            'info' => $employe,
        ));
    }

    public function collegeList2Action() {
        $tableCollege = new \RHX\Model\Table\CollegeTable($this->getAdapter());
        $collegeList = $tableCollege->getAll('id DESC');
        $colleges = array();
        foreach ($collegeList as $c) {
            $colleges[$c->id] = $c->libelle;
        }
    }

    /**
     * Effacer diplome d'un employé
     * 
     * @return \Zend\View\Model\JsonModel
     */
    public function deleteDiplomeAction() {
        $tableEmployeDiplome = new \RHX\Model\Table\EmployeDiplomeTable($this->getAdapter());
        $post = $this->getRequest()
                ->getPost();
        $done = false;
        $diplome = $tableEmployeDiplome->get($post->id)
                ->getDiplome();
        if ($tableEmployeDiplome->erase($post->id) > 0) {
            $done = true;
        }

        return new JsonModel(array(
            'done' => $done,
            'diplome' => $diplome,
                )
        );
    }

    /**
     * Effacer une formation d'un employé
     *
     * @return \Zend\View\Model\JsonModel
     */
    public function deleteFormationAction() {
        $tableEmployeFormation = new \RHX\Model\Table\EmployeFormationTable($this->getAdapter());
        $post = $this->getRequest()
                ->getPost();
        $done = false;
        $formation = $tableEmployeFormation->get($post->id)
                ->getFormation();
        if ($tableEmployeFormation->erase($post->id) > 0) {
            $done = true;
        }

        return new JsonModel(array(
            'done' => $done,
            'formation' => $formation,
        ));
    }
    
    public function uploadPhotoAction() {
        $this->layout('layout/iframe2');
        
        // config 
        $config = $this->getServiceLocator()->get('config');        
        $repPhoto = $config['upload_directory']['employe']['photo'];
        
        $query = $this->getRequest();
        $matricule = (int) $this->params()
                        ->fromRoute('id', 0);
        if ($query->isPost()) {
            //echo "<pre>POST</pre>";
            $post = $query->getPost();
            $matricule = (int) $post->matricule;
//	    $name	 = 'module/RHX/data/photo/' . rand() . '.jpg';
            $random = rand();
            
            //$name = "public/upload/photo/$random.jpg";
            $name = $repPhoto.$random.'.jpg';
            
            // Téléchargement du fichier PHOTO
            $extensions = array('jpg', 'png', 'gif');
            $result = Uploader::upload('photo', $name, FALSE, $extensions );
            $result['destination'] = "$random.jpg";
            //Debug::dump($result, "Résultat upload");
            if ($result['done']) {
                //echo "<pre>DONE = true</pre>";
                $post = $query->getPost();
                $matricule = (int) $post->matricule;
                if ($matricule != 0) {
                    // Mise à jour des données
                    $newName =                             $repPhoto. 'photo-' . $matricule . '.' . $result['extension'];
                    $newName2 = str_replace('public/', '', $repPhoto) . 'photo-' . $matricule . '.' . $result['extension'];
                    // renommer fichier
                    if (@rename($name, $newName) || @rename($name,  $newName2)) {
                        $result['destination'] = 'photo-' . $matricule . '.' . $result['extension'];
                    }
                }
                return array(
                    'matricule' => $matricule,
                    'fichier' => $result['name'],
                    'destination' => $result['destination'],
                    'repPhoto' => $repPhoto,
                    'extension' => $result['extension'],
                    'error' => $result['error'],
                );
            }
            elseif( $result['error'] ){
                 return array(
                    'matricule' => $matricule,                    
                    'error' => $result['error'],                    
                );
            }
        }
        return array(
            'matricule' => $matricule,
            'fichier' => null,
        );
    }
    /* retourner liste des employé selon les poste
     * 
     */
    public function jsonDirecteurAction() {
        //$this->layout('layout/rhx2.phtml');
        
        $idSite = (int) $this->params()->fromRoute('id', 0);
        
        // Table
        $employeTbl = $this->getService('Table\EmployeTable');
        $avTbl = $this->getService('Table\AvenantTable');
        $pstTbl = $this->getService('Table\PosteTable');
        $siteTbl = $this->getService('Table\SiteTable');
        
        //$empList = $employeTbl->getAll();
        $empList = $employeTbl->getByPoste('directeur', $idSite);
        
        $employes = array();
        foreach ($empList as $k => $emp) {
            $av = $avTbl->get($emp->avenant_id);
            $pst = $pstTbl->get($av->poste_id);
            
            $employes[$emp->matricule] =  $pst->code . ' - ' . $emp->nom1 . ' ' . $emp->prenom ;
        }

        $json = new \Zend\View\Model\JsonModel($employes);        
        //var_dump($employes);
        return $json;
        
    }
    
    /**
     * Boite de dialogue pour l'affichage du changement de site
     * 
     * @return \Zend\View\Model\ViewModel
     */
    public function changeSiteAction(){
	$this->layout('layout/ajax');
	$manager = new \RHX\Model\Manager\EmployeManager($this->getAdapter());
	return $manager->showChangeSiteDialog($this->getPost());
    }
    
    /**
     * Application du changement de site
     * 
     * @return JsonModel
     */
    public function applyChangeSiteAction(){
	$this->layout('layout/ajax');
	$manager = new \RHX\Model\Manager\EmployeManager($this->getAdapter());
	return $manager->applyChangeSite($this->getPost());
    }
    
    /* Annule le changement de site
     */
    
    public function cancelTransfertAction(){
        $this->layout('layout/ajax');
        
        $post = $this->getPost();
        $manager = new \RHX\Model\Manager\EmployeManager($this->getAdapter());
        
        return $manager->cancelTranfert($post);
        //return array('info' => '');
    }

    /**
     * Imprimer le Contrat
     * 
     * @return \Zend\View\Model\JsonModel
     */
    public function printContratAction(){
	$this->layout('layout/ajax');
	$post = $this->getPost();
	$manager = new \RHX\Model\Manager\DocxManager($this->getAdapter(), $this->getPublicPath());
	$manager->export($post->matricule);
//	return new JsonModel(array(
//	    'done' => true,
//	    'path' => $this->getPublicPath(),
//	));
    }
    
    /*
    public function testAction(){
        $manager = new \RHX\Model\Manager\EmployeManager($this->getAdapter());
        $matricule = 292;
        try{
            $manager->deleteEmploye($matricule);
        }
        catch(\Exception $ex){
            var_dump($ex);
        }
        die;
    }
    */
}
